package zhizhemodi.tech.short_term_bwork.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import zhizhemodi.tech.short_term_bwork.entity.Department;
import zhizhemodi.tech.short_term_bwork.entity.Device;
import zhizhemodi.tech.short_term_bwork.mapper.DepartmentMapper;
import zhizhemodi.tech.short_term_bwork.tool.CommonResult;
import zhizhemodi.tech.short_term_bwork.service.DeviceService;;

@RestController
@RequestMapping("department")
public class DepartmentController {

    // 默认每页条数
    @Value("${default.page.rowNum}")
    Integer ROW_MAX;
    
    @Autowired
    DepartmentMapper departmentMapper;

    /**
     * 获取机构信息
     * 新增分页功能
     * @param key
     * @return
     */
    @GetMapping("list")
    public CommonResult<?> getDepartmentList(
        @RequestParam(required = false, name = "key") String key,
        @RequestParam(required = false, name = "limit") Integer rowNum,
        @RequestParam(required = false, name = "page") Integer pageNum
    ) {
        List<Department> dList = new ArrayList<Department>();
        try {
            QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
            if(key != null) {
                queryWrapper.like("department_id", key);
            }
            // 分页操作
            String last = null;
            if(pageNum == null) pageNum = 0;
            // 计算页数偏移量
            if(rowNum != null){
                last = " limit " + pageNum * rowNum + "," + rowNum; 
            }
            else {
                last = " limit " + pageNum * ROW_MAX + "," + ROW_MAX;
            }
            queryWrapper.last(last);
            dList = departmentMapper.selectList(queryWrapper);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        Map<Object, Object> re = new HashMap<>();
        re.put("list", dList);
        re.put("page", pageNum);
        return CommonResult.success(re);
    }

    /**
     * 新增机构
     * @param departmentName
     * @param departmentChar
     * @return
     */
    @PostMapping("add")
    public CommonResult<?> addDepartment(
        @RequestParam("departmentName") String departmentName,
        @RequestParam("departmentChar") String departmentChar
    ) {
        try{
            QueryWrapper<Department> queryWrapper = new QueryWrapper<Department>();
            queryWrapper.eq("department_name", departmentName);
            if(departmentMapper.exists(queryWrapper)){
                throw new Exception("机构名重复！");
            }
            List<Department> dList = departmentMapper.selectList(null);
            Integer next_id = 0;
            if(dList != null) next_id = dList.get(dList.size() - 1).getDepartmentId() + 1;
            Department department = new Department(next_id, departmentName, departmentChar);
            departmentMapper.insert(department);
        }catch (Exception e){   
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success("添加成功");
    }

    /**
     * 更新机构名称或机构编码
     * @param newName
     * @param newChar
     * @param dId
     * @return
     */
    @PutMapping("update")
    public CommonResult<?> updateDepartmentName(
        @RequestParam(required = false, name = "newName") String newName,
        @RequestParam(required = false, name = "newChar") String newChar,
        @RequestParam("departmentId") Integer dId) {
        int re = 0;
        try{
            if(newName != null) re = re + departmentMapper.updateName(newName, dId);
            if(newChar != null) re = re + departmentMapper.updateChar(newChar, dId);
        } catch(Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        if(re >= 1) return CommonResult.success(re);
        else return CommonResult.failed("修改失败");
    }

    // 设备表映射
    @Resource
    DeviceService deviceService;

    /**
     * 删除机构
     * @param dId
     * @return
     */
    @DeleteMapping("delete")
    public CommonResult<?> deleteDepartment(@RequestParam("dId") Integer dId) {
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.eq("department_id", dId);
        try {
            List<Device> devices = deviceService.findDevice("department_id", dId);
            for(Device item : devices) deviceService.deleteDevices(item.getDeviceId());
            departmentMapper.delete(departmentQueryWrapper);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success("Delete success!");
    }
}
